<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
      v-if="searchState"
    >
      <el-form-item label="商铺编号" prop="shopsId">
        <HouseInput v-model="queryParams.code"></HouseInput>
      </el-form-item>
      <el-form-item label="付款方式" prop="payId">
        <el-select v-model="queryParams.payId" placeholder="请选择">
          <el-option
            v-for="item in paymentmethodList"
            :key="item.id"
            :label="item.name"
            :value="parseInt(item.id)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="state">
        <el-select
          v-model="queryParams.state"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.zhwy_advance_deposit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:advancedeposit:add']"
          >预存</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleUpdate"
          v-hasPermi="['system:advancedeposit:edit']"
          >退还</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:advancedeposit:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="advancedepositList" border>
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="收费项目" align="center" prop="chargeitemName" />
      <el-table-column label="收费金额" align="center" prop="amt">
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0">{{ scope.row.amt }}</span>
          <span v-else>{{ "-" + scope.row.amt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="付款方式" align="center" prop="payName" />
      <el-table-column
        label="收款时间"
        align="center"
        prop="payTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.payTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="收款人" align="center" prop="chargeUser" />
      <el-table-column label="单号" align="center" prop="payNo" />
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.zhwy_advance_deposit"
            :value="scope.row.state"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            :disabled="scope.row.state == 0 ? false : true"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:advancedeposit:edit']"
            >打印收款单</el-button
          >
          <el-button
            :disabled="scope.row.state != 0 ? false : true"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:advancedeposit:remove']"
            >打印退款单</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预存款管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="编号" prop="code">
          <HouseInput v-model="form.code"></HouseInput>
          <el-button type="primary" @click="searchName" v-if="title == '预存款'"
            >搜索</el-button
          >
          <el-button
            type="primary"
            @click="findBalance"
            v-if="title != '预存款'"
            >搜索</el-button
          >
        </el-form-item>

        <el-form-item label="客户姓名" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入"
            :disabled="true"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="可用收费项"
          prop="type"
          v-if="title != '退还预存款'"
        >
          <el-radio-group v-model="form.type">
            <el-radio
              v-for="dict in dict.type.zhwy_advance_deposit_type"
              :key="dict.value"
              :label="parseInt(dict.value)"
              >{{ dict.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="收费项" prop="chargeitemId" v-if="form.type == 0">
          <el-select v-model="form.chargeitemId" placeholder="请选择">
            <el-option
              v-for="item in chargeList"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="收费金额" prop="amt" v-if="title != '退还预存款'">
          <el-input v-model="form.amt" placeholder="请输入收费金额" />
        </el-form-item>
        <el-form-item
          label="付款方式"
          prop="payId"
          v-if="title != '退还预存款'"
        >
          <el-select v-model="form.payId" placeholder="请选择">
            <el-option
              v-for="item in paymentmethodList"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="收款时间"
          prop="payTime"
          v-if="title != '退还预存款'"
        >
          <el-date-picker
            clearable
            v-model="form.payTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择收款时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="退款方式"
          prop="payId"
          v-if="title == '退还预存款'"
        >
          <el-select v-model="form.payId" placeholder="请选择">
            <el-option
              v-for="item in paymentmethodList"
              :key="item.id"
              :label="item.name"
              :value="parseInt(item.id)"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="退还时间"
          prop="refundTime"
          v-if="title == '退还预存款'"
        >
          <el-date-picker
            clearable
            v-model="form.refundTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退款时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-tabs value="first" v-if="title == '退还预存款'">
          <el-tab-pane label="剩余预存款" name="first">
            <el-table :data="refundList" border>
              <el-table-column label="序号" prop="id"></el-table-column>
              <el-table-column label="收费项" prop="chargeitemName">
              </el-table-column>
              <el-table-column
                label="账户余额"
                prop="balance"
              ></el-table-column>
              <el-table-column label="退还金额" prop="amt">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.amt"></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="title == '预存款'"
          >确 定</el-button
        >
        <el-button type="primary" @click="submitRefundForm" v-else
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAdvancedeposit,
  getAdvancedeposit,
  delAdvancedeposit,
  addAdvancedeposit,
  updateAdvancedeposit,
  groupListAdvancedeposit,
} from "@/api/system/advancedeposit";
import {
  listPaymentmethod,
  getPaymentmethod,
} from "@/api/system/paymentmethod";
import { listChargeitem, getChargeitem } from "@/api/charge/chargeitem";
import {
  listRentalcontract,
  getRentalcontract,
} from "@/api/rentalcontract/rentalcontract";
import { listHirer } from "@/api/renter/hirer";
import { number } from "echarts";
import { listShops, getShops } from "@/api/shops/shops";
import { getUserProfile } from "@/api/system/user";

export default {
  name: "Advancedeposit",
  props: {
    value: {
      type: Number,
      default: null,
    },
    searchState: {
      type: Boolean,
      default: true,
    },
  },
  dicts: ["zhwy_advance_deposit", "zhwy_advance_deposit_type"],
  watch: {
    value: {
      immediate: true,
      handler(val) {
        this.queryParams.shopsId = val;
        this.getList();
      },
    },
    searchState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getList();
        }
      },
    },
  },
  data() {
    return {
      // 退款表单数据
      refundList: [],
      // 收费项列表
      chargeList: [],
      // 支付方式列表
      paymentmethodList: [],
      // 用户信息
      userInfo: {
        chargeUser: null,
        refundUser: null,
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预存款管理表格数据
      advancedepositList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        shopsId: null,
        chargeitemId: null,
        payId: null,
        state: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        amt: [
          {
            required: true,
            message: "收费金额不能为空",
            trigger: "blur",
            type: "number",
            transform: (value) => {
              return Number(value);
            },
          },
        ],
        shopsId: [
          { required: true, message: "编号不能为空", trigger: "change" },
        ],
        code: [{ required: true, message: "编号不能为空", trigger: "change" }],
        name: [
          { required: true, message: "请输入编号后点击搜索", trigger: "blur" },
        ],
        type: [
          { required: true, message: "请选择收费项类型", trigger: "blur" },
        ],
        chargeitemId: [
          { required: true, message: "收费项不能为空", trigger: "blur" },
        ],
        payId: [
          { required: true, message: "付款方式不能为空", trigger: "blur" },
        ],
        refundId: [
          { required: true, message: "付款方式不能为空", trigger: "blur" },
        ],
        payTime: [
          { required: true, message: "收款时间不能为空", trigger: "blur" },
        ],
        refundTime: [
          { required: true, message: "收款时间不能为空", trigger: "blur" },
        ],
        amt: [{ required: true, message: "收费金额不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
    this.getUserInfo();
    this.getPayment();
    this.getChargeList();
    this.reset();
  },
  methods: {
    // 退款表单提交
    async submitRefundForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            // 遍历 refundList
            for (let item of this.refundList) {
              if (item.balance - item.amt > 0) {
                // 为每个退款项创建一个新的表单对象
                const refundForm = {
                  refundTime: this.form.refundTime,
                  payId: this.form.payId,
                  shopsId: this.form.shopsId,
                  state: 1,
                  refundUser: this.userInfo.refundUser,
                  balance: item.balance - item.amt,
                  amt: item.amt,
                  chargeitemId: item.chargeitemId,
                };
                if (item.amt != null && item.amt != 0 && item.amt != "") {
                  // 提交每个退款项
                  const res = await addAdvancedeposit(refundForm);
                  if (res.code !== 200) {
                    // 如果某个退款项提交失败，可以选择抛出错误或继续处理其他项
                    throw new Error(res.msg);
                  }
                }
              } else {
                this.$message.warning("退款金额不能大于余额");
              }
            }

            // 所有退款项处理完毕后显示成功消息
            this.$modal.msgSuccess("退款项退还成功");
            this.open = false;
            this.getList();
            this.resetQuery();
            this.refundList = [];
          } catch (error) {
            // 如果有任何错误，显示错误信息
            this.$modal.msgError(error.message);
          }
        }
      });
    },

    // 查看余额
    async findBalance() {
      try {
        // 获取店铺信息
        const shopRes = await listShops({ code: this.form.code });
        if (shopRes.code !== 200) {
          throw new Error(shopRes.msg);
        }
        this.form.shopsId = shopRes.rows[0].id;
        this.resetQuery();
        this.queryParams.shopsId = this.form.shopsId;
        // 获取预付款信息
        const advanceDepositRes = await groupListAdvancedeposit(
          this.queryParams
        );
        if (advanceDepositRes.code !== 200) {
          throw new Error(advanceDepositRes.msg);
        }
        this.refundList = advanceDepositRes.rows;

        // 获取每个预付款项的 chargeItemName
        const chargeItemPromises = this.refundList.map(async (item) => {
          const chargeItemRes = await getChargeitem(item.chargeitemId);
          if (chargeItemRes.code === 200) {
            item.chargeitemName = chargeItemRes.data.name;
          }
        });

        // 等待所有的 chargeItemPromises 完成
        await Promise.all(chargeItemPromises);

        // 现在可以安全地打印 this.refundList，因为所有的 chargeItemName 都已经被填充
        console.log(this.refundList);

        // 获取租赁合同和承租人信息（这部分可以类似地处理）
        const rentalContractRes = await listRentalcontract({
          shopsId: this.form.shopsId,
        });
        if (rentalContractRes.code === 200) {
          if (
            rentalContractRes.rows[0].hirerId == null &&
            rentalContractRes.rows[0].hirerId == ""
          ) {
            return this.$message.warning("没有该用户信息！");
          }
          const hirerRes = await listHirer({
            id: rentalContractRes.rows[0].hirerId,
          });
          if (hirerRes.code === 200) {
            this.form.name = hirerRes.rows[0].name;
          } else {
            this.$message.error("没有找到该租户信息!");
          }
        } else {
          this.$message.error(rentalContractRes.msg);
        }
      } catch (error) {
        this.$message.error(error.message);
      }
    },
    // 搜索客户姓名
    searchName() {
      listShops({ code: this.form.code }).then((res) => {
        if (res.code == 200) {
          this.form.shopsId = res.rows[0].id;
          listRentalcontract({ shopsId: this.form.shopsId }).then((res) => {
            if (res.code == 200) {
              listHirer({ id: res.rows[0].hirerId }).then((res) => {
                if (res.code == 200) {
                  this.form.name = res.rows[0].name;
                } else {
                  this.$message.error(res.msg);
                }
              });
            } else {
              this.$message.error(res.msg);
            }
          });
        }
      });
    },
    // 获取收费项目
    getChargeList() {
      listChargeitem({}).then((res) => {
        this.chargeList = res.rows;
      });
    },
    // 获取所有支付方式
    getPayment() {
      listPaymentmethod().then((response) => {
        this.paymentmethodList = response.rows;
      });
    },
    // 查询当前用户信息
    getUserInfo() {
      getUserProfile().then((resp) => {
        console.log(resp);
        this.userInfo.chargeUser = resp.data.nickName;
        this.userInfo.refundUser = resp.data.nickName;
        console.log(this.userInfo);
      });
    },
    /** 查询预存款管理列表 */
    getList() {
      this.loading = true;

      listAdvancedeposit(this.queryParams).then((response) => {
        if (response.code == 200) {
          this.advancedepositList = response.rows;
          this.loading = false;
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.refundList = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        shopsId: null,
        type: null,
        name: null,
        code: null,
        chargeitemId: null,
        amt: null,
        payId: null,
        payTime: null,
        chargeUser: null,
        payNo: null,
        payType: null,
        state: null,
        balance: null,
        refundUser: null,
        refundTime: null,
        refundId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.queryParams.code != null && this.queryParams.code != "") {
        listShops({ code: this.queryParams.code }).then((res) => {
          if (res.code == 200) {
            this.queryParams.shopsId = res.rows[0].id;
            this.getList();
          }
        });
      } else {
        this.getList();
      }
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "预存款";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset();
      this.open = true;
      this.title = "退还预存款";
    },
    /** 提交按钮 */
    async submitForm() {
      try {
        // 验证表单
        // await this.$refs["form"].validatePromise();
        this.$refs["form"].validate(async (valid) => {
          if (valid) {
            // 获取店铺信息
            const shopsRes = await listShops({ code: this.form.code });
            if (shopsRes.code !== 200) {
              throw new Error(shopsRes.msg || "获取店铺信息失败");
            }
            if (
              this.form.chargeitemId != null &&
              this.form.chargeitemId != ""
            ) {
              this.form.chargeitemId == 0;
            }
            // 设置表单的shopsId和其他属性
            this.form.state = 0;
            this.form.chargeUser = this.userInfo.chargeUser;
            this.form.shopsId = shopsRes.rows[0].id;

            // 如果shopsId有效，则获取分组预存款信息
            if (this.form.shopsId && this.form.shopsId !== "") {
              const groupRes = await groupListAdvancedeposit({
                shopsId: this.form.shopsId,
                chargeitemId: this.form.chargeitemId,
              });
              if (groupRes.code !== 200) {
                throw new Error(groupRes.msg || "获取分组预存款信息失败");
              }

              // 更新表单的balance属性
              this.form.balance =
                parseInt(this.form.amt) + parseInt(groupRes.rows[0].balance);
            }

            // 提交预存款信息
            const addRes = await addAdvancedeposit(this.form);
            if (addRes.code !== 200) {
              throw new Error(addRes.msg || "新增预存款失败");
            }

            // 显示成功消息并关闭弹窗，刷新列表
            this.$modal.msgSuccess("新增成功");
            this.open = false;
            this.getList();
          }
        });
      } catch (error) {
        // 显示错误消息
        this.$modal.msgError(error.message);
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除预存款管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delAdvancedeposit(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/advancedeposit/export",
        {
          ...this.queryParams,
        },
        `advancedeposit_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
